#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QFileDialog>

#include "DetectRegions.h"

using namespace std;
using namespace cv;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    saveRegions = false;
    showSteps = false;
}

MainWindow::~MainWindow()
{
    delete ui;
}

string MainWindow::getFilename(string s) {

    char sep = '/';
    char sepExt='.';

    #ifdef _WIN32
        sep = '\\';
    #endif

    size_t i = s.rfind(sep, s.length( ));
    if (i != string::npos) {
        string fn= (s.substr(i+1, s.length( ) - i));
        size_t j = fn.rfind(sepExt, fn.length( ));
        if (i != string::npos) {
            return fn.substr(0,j);
        }else{
            return fn;
        }
    }else{
        return "";
    }
}


void MainWindow::on_openImageBtn_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(this,
            tr("Open Image"), ".", tr("Image Files (*.png *.jpg *.bmp)"));
    input_image = imread(fileName.toUtf8().data(),1);
    if(input_image.data) {

        filename_whithoutExt=getFilename(fileName.toStdString());
        cout << "working with file: "<< filename_whithoutExt << "\n";
    }
}

void MainWindow::on_applyANPRBtn_clicked()
{
    if (filename_whithoutExt.length()<4)
        return;
    // Detect posibles plate regions
    DetectRegions detectRegions;
    detectRegions.setFilename(filename_whithoutExt);
    detectRegions.saveRegions=saveRegions;
    detectRegions.showSteps=showSteps;
    vector<Plate> posible_regions= detectRegions.run( input_image );
}

void MainWindow::on_saveRgn_toggled(bool checked)
{
    saveRegions = checked;
}

void MainWindow::on_showSteps_toggled(bool checked)
{
    showSteps = checked;
}

